package com.lw.leetcode.str.b;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 833. 字符串中的查找与替换
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/22 21:23
 */
public class FindReplaceString {


    public static void main(String[] args) {
        FindReplaceString test = new FindReplaceString();

        //  eeecd
        String str = "abcd";
        int[] arr = {0, 2};
        String[] a = {"a", "ec"};
        String[] b = {"eee", "ffff"};

        // eeebffff
//        String str = "abcd";
//        int[] arr = {0,2};
//        String[] a = {"a","cd"};
//        String[] b = {"eee","ffff"};

        // "vbfrssozp"
//        String str = "vmokgggqzp";
//        int[] arr = {3,5,1};
//        String[] a = {"kg","ggq","mo"};
//        String[] b = {"s","so","bfr"};

        String replaceString = test.findReplaceString(str, arr, a, b);
        System.out.println(replaceString);
    }

    public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
        int l = s.length();
        int length = indices.length;
        StringBuilder sb = new StringBuilder();
        List<Node> list = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            int v = indices[i];
            String a = sources[i];
            if (a.equals(s.substring(v, v + a.length()))) {
                list.add(new Node(v, a.length(), targets[i]));
            }
        }
        list.sort((a, b) -> Integer.compare(a.v, b.v));
        int item = 0;
        length = list.size();
        for (int i = 0; i < l; i++) {
            if (item < length && i == list.get(item).v) {
                sb.append(list.get(item).b);
                i += list.get(item).a - 1;
                item++;
            } else {
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }

    class Node {
        public Node(int v, int a, String b) {
            this.v = v;
            this.a = a;
            this.b = b;
        }

        private int v;
        private int a;
        private String b;
    }


}
